package com.tianji.aigc.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.aigc.entity.ChatSession;
import com.tianji.aigc.mapper.ChatSessionMapper;
import com.tianji.aigc.properties.SessionProperties;
import com.tianji.aigc.service.IChatSessionService;
import com.tianji.aigc.vo.SessionVO;
import com.tianji.common.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 对话session 服务实现类
 * </p>
 *
 * @author gzl
 * @since 2025-09-02
 */
@Service
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession> implements IChatSessionService {
    @Autowired
    private SessionProperties sessionProperties;


    /**
     * 新建会话
     * @param num
     * @return
     */

    @Override
    public SessionVO createSession(Integer num) {
        //生成会话id
        String sessionId = IdUtil.fastSimpleUUID();

        //保存会话历史
        ChatSession chatSession = ChatSession.builder()
                .sessionId(sessionId)
                .userId(UserContext.getUser())
                .build();
        save(chatSession);

        //抽取三个热门问题
        List<SessionVO.Example> list = sessionProperties.getExamples();
        //打乱顺序，达到随机的目的
        Collections.shuffle(list);

        //封装数据，返回
        SessionVO sessionVO = SessionVO.builder()
                .sessionId(sessionId)
                .title(sessionProperties.getTitle())
                .describe(sessionProperties.getDescribe())
                .examples(list.subList(0, Math.min(num, list.size())))
                .build();

        return sessionVO;
    }


    /**
     * 热门问题
     * @param num
     * @return
     */
    @Override
    public List<SessionVO.Example> hotExample(Integer num) {
        //抽取三个热门问题
        List<SessionVO.Example> list = sessionProperties.getExamples();
        //打乱顺序，达到随机的目的
        Collections.shuffle(list);
        List<SessionVO.Example> examplesList = list.subList(0, Math.min(num, list.size()));
        return examplesList;
    }

}
